-- Copyright (c) 2025 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at:
--         http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local skynet = require 'skynet'
local log = require 'mc.logging'
local definition = require 'canbus.definition'

skynet.register_protocol({
    name = 'CAN-FD',
    id = definition.can_protocol_id,
    pack = skynet.pack,
    unpack = skynet.unpack
})

return function(worker)
    local driver_ok, canbus_driver = pcall(require, 'libsoc_adapter.canbus')
    if not driver_ok then
        log:error('load canbus driver failed, error: %s', canbus_driver)
        return
    end

    local channel = worker:recv()
    log:notice('canbus [%s] recv worker is started ...', channel)

    local driver = canbus_driver.new(channel)
    driver:init()
    local options = {
        definition.can_frame_max_size.CANFD + 4,  -- 读取时需要包含canid的4个字节
        definition.can_frame_timeout.RECV,
        definition.can_frame_type.CANFD
    }
    local ok, msg
    while worker:is_running() do
        -- NOTE: read 2nd argument is can_id, current is useless for driver and fixed to 0
        ok, msg = pcall(driver.read, driver, 0, table.unpack(options))
        if not ok then
            log:info('canbus [%s] read from canbus failed, error: %s', channel, msg)
            goto continue
        end
        if msg == '' then
            goto continue
        end
        skynet.send('.bmc_datasync', 'CAN-FD', 'recv', {channel = channel, msg = msg})
        ::continue::
        worker:sleep(300)  -- 300用于出线程
    end
end